"""
检验单查询相关API
"""
from flask import Blueprint, jsonify, request
from app.services.inspection_service import InspectionService
from app.utils.response import success_response, error_response
from app.utils.auth import require_auth
import logging

logger = logging.getLogger(__name__)
inspection_bp = Blueprint('inspection', __name__, url_prefix='/yonbip/QMS_QIT')


@inspection_bp.route('/checkapply/list', methods=['POST'])
def get_inspection_list():
    """检验申请列表查询"""
    try:
        data = request.get_json()

        # 如果没有传递数据，使用默认值
        if not data:
            data = {}

        # 设置默认分页参数
        page_index = data.get('pageIndex', 1)
        page_size = data.get('pageSize', 10)

        # 验证分页参数
        if page_index < 1:
            page_index = 1
        if page_size < 1 or page_size > 100:
            page_size = 10

        logger.info(f"检验申请列表查询: pageIndex={page_index}, pageSize={page_size}, 查询条件={data}")

        result = InspectionService.query_inspection_list(data)

        return jsonify({
            "code": "0",
            "message": "success",
            "data": result
        })

    except ValueError as e:
        logger.error(f"检验申请列表查询参数错误: {str(e)}")
        return jsonify({
            "code": "400",
            "message": str(e),
            "data": None
        }), 400
    except Exception as e:
        logger.error(f"检验申请列表查询异常: {str(e)}")
        return jsonify({
            "code": "500",
            "message": f"查询失败: {str(e)}",
            "data": None
        }), 500


@inspection_bp.route('/checkapply/detail', methods=['GET'])
def get_inspection_detail():
    """检验申请详情查询"""
    try:
        # 获取查询参数
        access_token = request.args.get('access_token')
        billnum = request.args.get('billnum', 'qms_LLCheckApply_card')
        inspection_id = request.args.get('id')
        inspection_code = request.args.get('code')

        # 验证必要参数
        if not inspection_id and not inspection_code:
            return jsonify({
                "code": "400",
                "message": "参数错误：id 或 code 至少需要提供一个",
                "data": None
            }), 400

        logger.info(f"检验申请详情查询: id={inspection_id}, code={inspection_code}, billnum={billnum}")

        result = InspectionService.query_inspection_detail(
            inspection_id=inspection_id,
            inspection_code=inspection_code,
            billnum=billnum
        )

        if not result:
            return jsonify({
                "code": "404",
                "message": "未找到指定的检验申请记录",
                "data": None
            }), 404

        return jsonify({
            "code": "0",
            "message": "success",
            "data": result
        })

    except ValueError as e:
        logger.error(f"检验申请详情查询参数错误: {str(e)}")
        return jsonify({
            "code": "400",
            "message": str(e),
            "data": None
        }), 400
    except Exception as e:
        logger.error(f"检验申请详情查询异常: {str(e)}")
        return jsonify({
            "code": "500",
            "message": f"查询失败: {str(e)}",
            "data": None
        }), 500


@inspection_bp.route('/inspectorder/save', methods=['POST'])
def save_inspection_order():
    """检验单保存"""
    try:
        # 获取查询参数
        access_token = request.args.get('access_token')

        # 获取请求体数据
        data = request.get_json()

        if not data:
            return jsonify({
                "code": "400",
                "message": "请求体不能为空",
                "data": None
            }), 400

        logger.info(f"检验单保存请求: access_token={access_token}, data={data}")

        result = InspectionService.save_inspection_order(data)

        return jsonify({
            "code": "0",
            "message": "success",
            "data": result
        })

    except ValueError as e:
        logger.error(f"检验单保存参数错误: {str(e)}")
        return jsonify({
            "code": "400",
            "message": str(e),
            "data": None
        }), 400
    except Exception as e:
        logger.error(f"检验单保存异常: {str(e)}")
        return jsonify({
            "code": "500",
            "message": f"保存失败: {str(e)}",
            "data": None
        }), 500


@inspection_bp.route('/inspectorder/confirm', methods=['POST'])
def confirm_inspection_order():
    """检验单确认"""
    try:
        # 获取查询参数
        access_token = request.args.get('access_token')

        # 获取请求体数据
        data = request.get_json()

        if not data:
            return jsonify({
                "code": "400",
                "message": "请求体不能为空",
                "data": None
            }), 400

        # 验证必要参数
        code = data.get('code')
        inspection_id = data.get('id')

        if not code and not inspection_id:
            return jsonify({
                "code": "400",
                "message": "参数错误：code 或 id 至少需要提供一个",
                "data": None
            }), 400

        logger.info(f"检验单确认请求: access_token={access_token}, data={data}")

        result = InspectionService.confirm_inspection_order(data)

        return jsonify({
            "code": "0",
            "message": "success",
            "data": result
        })

    except ValueError as e:
        logger.error(f"检验单确认参数错误: {str(e)}")
        return jsonify({
            "code": "400",
            "message": str(e),
            "data": None
        }), 400
    except Exception as e:
        logger.error(f"检验单确认异常: {str(e)}")
        return jsonify({
            "code": "500",
            "message": f"确认失败: {str(e)}",
            "data": None
        }), 500